package Econf_Audio;
/*
 * @(#)AVReceive2.java    1.3 01/03/13
 *
 * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.util.Vector;

import javax.media.*;
import javax.media.rtp.*;
import javax.media.rtp.event.*;
import javax.media.rtp.rtcp.*;
import javax.media.protocol.*;
import javax.media.format.AudioFormat;
import javax.media.format.VideoFormat;
import javax.media.Format;
import javax.media.format.FormatChangeEvent;
import javax.media.control.BufferControl;

import model.Constantes;
import model.MainServer;
import model.UserServerDelegate;


/**
 * AVReceive2 to receive RTP transmission using the new RTP API.
 */
public class RTPServeur implements ReceiveStreamListener, SessionListener, 
    ControllerListener
{
	// Attributs
		RTPManager mgrs[] = null;
		RTPManager mgrsTransmit[] = null;
	    Vector playerWindows = null;
	    private static int portE;
	    boolean dataReceived = false;
	    Object dataSync = new Object();
		private int PortlocalTransmetteur;
		private int PortlocalReceveur;
		private String IPServeur;
		private String ttl;
		private Object[][] tabIPetInfoUser;
		private Object[][] tabUpdateConf;
		private int numeroDemande;
	
	// Observateurs
		public Object[][] getTabIPetInfoUser() {
			return tabIPetInfoUser;
		}
		public Object[][] getTabUpdateConf() {
			return tabUpdateConf;
		}
		
		public int getNumeroDemande() {
			return numeroDemande;
		}
		
	// Mutateur
		public void setTabIPetInfoUser(Object[][] tabIPetInfoUserTMP) {
			int tailleL = tabIPetInfoUserTMP.length;
			int tailleC = tabIPetInfoUserTMP[0].length;
			this.tabIPetInfoUser  = new Object[tailleL][tailleC];
			this.tabIPetInfoUser = tabIPetInfoUserTMP;
		}
		public void setTabUpdateConf(Object[][] TabUpdateConfTMP) {
			int tailleL = TabUpdateConfTMP.length;
			int tailleC = TabUpdateConfTMP[0].length;
			this.tabUpdateConf  = new Object[tailleL][tailleC];
			this.tabUpdateConf = TabUpdateConfTMP;
		}
		public void setNumeroDemande(int numeroDemande) {
			this.numeroDemande = numeroDemande;
		}
	
    // Constructeur
    public RTPServeur(String IPServeur, int PortlocalReceveur, int PortlocalTransmetteur, int PortPourEmmision) {
		this.PortlocalTransmetteur = PortlocalTransmetteur;
		this.PortlocalReceveur = PortlocalReceveur;
		this.IPServeur = IPServeur;
		this.portE = PortPourEmmision;
		ttl = "1";
		numeroDemande = 1;
		
		if (!initialize()) {
	        System.err.println("Failed to initialize the sessions.");
	        System.exit(-1);
	    }
	}

    // Methode initualize
    protected boolean initialize() {

        try {
        InetAddress ipAddr;
        SessionAddress localAddr = new SessionAddress();
        SessionAddress destAddr;

        mgrs = new RTPManager[1];
        mgrsTransmit = new RTPManager[1];
        playerWindows = new Vector();
        
        // Open the RTP sessions.
        for (int i = 0; i < 1; i++) {
	        System.err.println("  - Open RTP receveur session for: addr: " + IPServeur + " port: " + PortlocalReceveur + " ttl: " + ttl);
	        // RTPManager Primaire
	        mgrs[i] = (RTPManager) RTPManager.newInstance();
	        mgrs[i].addSessionListener(this);
	        mgrs[i].addReceiveStreamListener(this);
	
	        ipAddr = InetAddress.getByName(IPServeur);
	        destAddr = new SessionAddress( ipAddr, portE);
	        
	        localAddr= new SessionAddress(InetAddress.getLocalHost(), PortlocalReceveur);   
	        mgrs[i].initialize( localAddr);
	
	        // You can try out some other buffer size to see
	        // if you can get better smoothness.
	        BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
	        if (bc != null)
	            bc.setBufferLength(350);
	        destAddr = new SessionAddress( ipAddr, portE);  
	        mgrs[i].addTarget(destAddr);
        }
     // Open the RTP sessionsTransmetteur secondaire for transmetteur.
        for (int i = 0; i < 1; i++) {
            System.err.println("  - Open RTP transmetteur session for: addr: " + IPServeur + " port: " + PortlocalTransmetteur	 + " ttl: " + ttl);
	
	        mgrsTransmit[i] = (RTPManager) RTPManager.newInstance();
	        //Création d'une SessionAddress 
	        SessionAddress localaddr = new SessionAddress(InetAddress.getLocalHost(),PortlocalTransmetteur);
	        //Initialisation du RTPManager 
	        mgrsTransmit[i].initialize(localaddr);
        }
        
        } catch (Exception e){
            System.err.println("Cannot create the RTP Session: " + e.getMessage());
            return false;
        }

    // Wait for data to arrive before moving on.

    long then = System.currentTimeMillis();
    long waitingPeriod = 30000;  // wait for a maximum of 30 secs.

    try{
        synchronized (dataSync) {
        while (!dataReceived && 
            System.currentTimeMillis() - then < waitingPeriod) {
            if (!dataReceived)
            System.err.println("  - Waiting for RTP data to arrive...");
            else System.err.println("  - Data Arrive ...");
            dataSync.wait(1000);
            
        }
        }
    } catch (Exception e) {}

    if (!dataReceived) {
        System.err.println("No RTP data was received.");
        close();
        return false;
    }

        return true;
    }

    // Methode is Done
    
    public boolean isDone() {
    return playerWindows.size() == 0;
    }


    /**
     * Close the players and the session managers.
     */
    protected void close() {

    for (int i = 0; i < playerWindows.size(); i++) {
        try {
        ((PlayerWindow)playerWindows.elementAt(i)).close();
        } catch (Exception e) {}
    }

    playerWindows.removeAllElements();

    // close the RTP session.
    for (int i = 0; i < mgrs.length; i++) {
        if (mgrs[i] != null) {
                mgrs[i].removeTargets( "Closing session from AVReceive2");
                mgrs[i].dispose();
                mgrsTransmit[i].removeTargets( "Closing session from AVReceive2");
                mgrsTransmit[i].dispose();
        mgrs = null;
        mgrsTransmit = null;
        }
    }
    }


    PlayerWindow find(Player p) {
    for (int i = 0; i < playerWindows.size(); i++) {
        PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
        if (pw.player == p)
        return pw;
    }
    return null;
    }


    PlayerWindow find(ReceiveStream strm) {
    for (int i = 0; i < playerWindows.size(); i++) {
        PlayerWindow pw = (PlayerWindow)playerWindows.elementAt(i);
        if (pw.stream == strm)
        return pw;
    }
    return null;
    }


    /**
     * SessionListener.
     */
    public synchronized void update(SessionEvent evt) {
    if (evt instanceof NewParticipantEvent) {
        Participant p = ((NewParticipantEvent)evt).getParticipant();
        System.err.println("  - A new participant had just joined: " + p.getCNAME());
        for (int i = 0; i < 1; i++) {
	        BufferControl bc = (BufferControl)mgrs[i].getControl("javax.media.control.BufferControl");
	      if (bc != null)
	          bc.setBufferLength(350);
		      String[] ipParti = p.getCNAME().split("@");
		      System.err.println("Ip participant: "+ipParti[1]);
		        SessionAddress destAddr;
				try {
					destAddr = new SessionAddress( InetAddress.getByName(ipParti[1]), portE);
					mgrs[i].addTarget(destAddr);
					System.err.println("addTarget destAddr: "+destAddr);
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvalidSessionAddressException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
        }
        
    }
    }

	/**
     * ReceiveStreamListener
     */
    public synchronized void update( ReceiveStreamEvent evt) {
    	
    RTPManager mgr = (RTPManager)evt.getSource();
    Participant participant = evt.getParticipant();    // could be null.
    ReceiveStream stream = evt.getReceiveStream();  // could be null.

    if (evt instanceof RemotePayloadChangeEvent) {
        System.err.println("  - Received an RTP PayloadChangeEvent.");
        System.err.println("Sorry, cannot handle payload change.");
        System.exit(0);
    }
    
    else if (evt instanceof NewReceiveStreamEvent) {
    	System.err.println("NewReceiveStreamEvent");
        try {
        stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
        
        DataSource ds = stream.getDataSource();

        // Find out the formats.
        RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
        if (ctl != null){
            System.err.println("  - Recevied new RTP stream: " + ctl.getFormat());
        } else
            System.err.println("  - Recevied new RTP stream");
        
        if (participant == null)
            System.err.println("      The sender of this stream had yet to be identified.");
        else {
            System.err.println("      The stream comes from: " + participant.getCNAME()); 
        }

        
     // Notify intialize() that a new stream had arrived.
        synchronized (dataSync) {
            dataReceived = true;
            dataSync.notifyAll();
        }
        
        for (int i = 0; i < 1; i++) {
	        mgrsTransmit[i].addTarget(new SessionAddress(InetAddress.getLocalHost(), portE));
        }
        new Emetteur_serveur(ds, mgrsTransmit);

        } catch (Exception e) {
        System.err.println("NewReceiveStreamEvent exception " + e.getMessage());
        e.printStackTrace();
        return;
        }
        
    }

    else if (evt instanceof StreamMappedEvent) {

         if (stream != null && stream.getDataSource() != null) {
        DataSource ds = stream.getDataSource();
        // Find out the formats.
        RTPControl ctl = (RTPControl)ds.getControl("javax.media.rtp.RTPControl");
        System.err.println("  - The previously unidentified stream ");
        if (ctl != null)
            System.err.println("      " + ctl.getFormat());
        System.err.println("      had now been identified as sent by: " + participant.getCNAME());
         }
    }
    
    else if (evt instanceof ActiveReceiveStreamEvent) {

        if (stream != null && stream.getDataSource() != null) {
       //DataSource ds = stream.getDataSource();
       System.out.println("ActiveReceiveStreamEvent: "+participant.getCNAME());
        }
   }

    else if (evt instanceof ByeEvent) {

         System.err.println("  - Got \"bye\" from: " + participant.getCNAME());
         PlayerWindow pw = find(stream);
         if (pw != null) {
        pw.close();
        playerWindows.removeElement(pw);
         }
    }

    }


    /**
     * ControllerListener for the Players.
     */
    public synchronized void controllerUpdate(ControllerEvent ce) {

    Player p = (Player)ce.getSourceController();

    if (p == null)
        return;

    // Get this when the internal players are realized.
    if (ce instanceof RealizeCompleteEvent) {
        PlayerWindow pw = find(p);
        if (pw == null) {
        // Some strange happened.
        System.err.println("Internal error!");
        System.exit(-1);
        }
        pw.initialize();
        pw.setVisible(true);
        p.start();
    }

    if (ce instanceof ControllerErrorEvent) {
        p.removeControllerListener(this);
        PlayerWindow pw = find(p);
        if (pw != null) {
        pw.close();    
        playerWindows.removeElement(pw);
        }
        System.err.println("AVReceive2 internal error: " + ce);
    }

    }




    /**
     * GUI classes for the Player.
     */
    class PlayerWindow extends Frame {

    Player player;
    ReceiveStream stream;

    PlayerWindow(Player p, ReceiveStream strm) {
        player = p;
        stream = strm;
    }

    public void initialize() {
        add(new PlayerPanel(player));
    }

    public void close() {
        player.close();
        setVisible(false);
        dispose();
    }

    public void addNotify() {
        super.addNotify();
        pack();
    }
    }


    /**
     * GUI classes for the Player.
     */
    class PlayerPanel extends Panel {

    Component vc, cc;

    PlayerPanel(Player p) {
        setLayout(new BorderLayout());
        if ((vc = p.getVisualComponent()) != null)
        add("Center", vc);
        if ((cc = p.getControlPanelComponent()) != null)
        add("South", cc);
    }

    public Dimension getPreferredSize() {
        int w = 0, h = 0;
        if (vc != null) {
        Dimension size = vc.getPreferredSize();
        w = size.width;
        h = size.height;
        }
        if (cc != null) {
        Dimension size = cc.getPreferredSize();
        if (w == 0)
            w = size.width;
        h += size.height;
        }
        if (w < 160)
        w = 160;
        return new Dimension(w, h);
    }
    }

    static void prUsage() {
    System.err.println("Usage: AVReceive2 <session> <session> ...");
    System.err.println("     <session>: <address>/<port>/<ttl>");
    System.exit(0);
    }
    
    
    // Methode 
    public void addIPdansTabIDetInfoUser(String IP, UserServerDelegate usd, String displayName, String role) throws InvalidSessionAddressException, UnknownHostException, IOException{
    	 // add la référence de la conf et l'ajout dans le tabIdetRTPServer
			if (tabIPetInfoUser != null){
				Object[][] tabIDetInfoUserTMP = new Object[tabIPetInfoUser.length+1][tabIPetInfoUser[0].length];
				for (int i = 0; i < tabIPetInfoUser.length; i++) {
					for (int j = 0; j < tabIPetInfoUser[i].length; j++) {
						tabIDetInfoUserTMP[i][j]=tabIPetInfoUser[i][j];
					}
				}
				// Ajout dans la derniere ligne
				tabIDetInfoUserTMP[tabIPetInfoUser.length][0] = IP;
				tabIDetInfoUserTMP[tabIPetInfoUser.length][1] = usd;
				tabIDetInfoUserTMP[tabIPetInfoUser.length][2] = displayName;
				tabIDetInfoUserTMP[tabIPetInfoUser.length][3] = role;
				setTabIPetInfoUser(tabIDetInfoUserTMP);
			}else{
				Object[][] tabIDetInfoUserTMP = new Object[1][4];
				tabIDetInfoUserTMP[0][0] = IP;
				tabIDetInfoUserTMP[0][1] = usd;
				tabIDetInfoUserTMP[0][2] = displayName;
				tabIDetInfoUserTMP[0][3] = role;
				setTabIPetInfoUser(tabIDetInfoUserTMP);
			}
		// Update les target du mgr
			for (int i = 0; i < 1; i++) {
				System.out.println(" Ajout de l'IP "+IP+" dans le mgrsTransmit");
		        mgrsTransmit[i].addTarget(new SessionAddress(InetAddress.getByName(IP), portE));
		        System.out.println("Parti: "+mgrsTransmit[i].getAllParticipants().toString());
	        }
    }
    
    public boolean sendUpdateIHM(){
    	try {
    		if(tabUpdateConf != null){
        		for (int i = 0; i < tabIPetInfoUser.length; i++) {
        			// Lecture du deuxieme élément qui correspnd à la ref de UserServeurDelegate
//        			UserServerDelegate usd = (UserServerDelegate) tabIPetInfoUser[i][1];
//        			MainServer serveur = usd.getServeur();
        			
//        			serveur.EnvoiReponseACK(usd,""+tabUpdateConf.length ,true, usd.getOos());
//        			serveur.EnvoiObject2DFromServerToClient(usd, tabUpdateConf, usd.getOos());
        			
//        			serveur.EnvoiUpdateTabServerToClient(usd, tabUpdateConf, usd.getOos());
//        			
//        			System.out.println(" Attente du ACK client");
//    				serveur.ReceptionACKFromClient(usd, usd.getOis());
    				System.out.println("Run Agent pour IP "+tabIPetInfoUser[i][0].toString());
        			AgentUpdateClient auc = new AgentUpdateClient(tabIPetInfoUser[i][0].toString(), 2222, tabUpdateConf, tabIPetInfoUser[i][3].toString());
        			auc.run();
        			System.out.println("Fin Agent pour IP "+tabIPetInfoUser[i][0].toString());
    			}
        	}
		} catch (Exception e) {
			return false;
		}
    	return true;
    }
    
    public boolean addParticipantinUpdateIHM(String dn, String roleClient){
    	try {
    		int etatMicro = Constantes.MICRO_NO_OK;
    		
    		if(roleClient.equals(Constantes.ROLE_ORATEUR_STRING)) etatMicro = Constantes.MICRO_OK;
    		if(roleClient.equals(Constantes.ROLE_AUDITEUR_STRING)) etatMicro = Constantes.MICRO_NO_OK;
    		if(roleClient.equals(Constantes.ROLE_ADMINCONF_STRING)) etatMicro = Constantes.MICRO_NO_OK;
    		
    		if (tabUpdateConf != null){
				Object[][] tabUpdateConfTMP = new Object[tabUpdateConf.length+1][tabUpdateConf[0].length];
				for (int i = 0; i < tabUpdateConf.length; i++) {
					for (int j = 0; j < tabUpdateConf[i].length; j++) {
						tabUpdateConfTMP[i][j]=tabUpdateConf[i][j];
					}
				}
				// Ajout dans la derniere ligne
				tabUpdateConfTMP[tabUpdateConf.length][0] = dn;
				tabUpdateConfTMP[tabUpdateConf.length][1] = etatMicro;
				tabUpdateConfTMP[tabUpdateConf.length][2] = "";
				setTabUpdateConf(tabUpdateConfTMP);
			}else{
	    		Object[][] tabUpdateConfTMP = new Object[1][3];
	    		tabUpdateConfTMP[0][0] = dn;
	    		tabUpdateConfTMP[0][1] = etatMicro;
	    		tabUpdateConfTMP[0][2] = "";
				setTabUpdateConf(tabUpdateConfTMP);
			}
		} catch (Exception e) {
			return false;
		}
    	return true;
    }
      
    
    public boolean addConferencierinUpdateIHM(String dn){
    	try {
    		Object[][] tabUpdateConfTMP = new Object[1][3];
    		tabUpdateConfTMP[0][0] = dn;
    		tabUpdateConfTMP[0][1] = Constantes.MICRO_OK;
    		tabUpdateConfTMP[0][2] = "";
			setTabUpdateConf(tabUpdateConfTMP);
        	
		} catch (Exception e) {
			return false;
		}
    	return true;
    }
    
    public boolean delParticipantinUpdateIHM(String dn){
    	try {
    		if (tabUpdateConf != null && tabUpdateConf.length > 1){
				Object[][] tabUpdateConfTMP = new Object[tabUpdateConf.length-1][tabUpdateConf[0].length];
				for (int i = 0; i < tabUpdateConf.length; i++) { 
					if (tabUpdateConf[i][0].equals(dn)){
						System.out.println("ne rien faire pour delpart");
					}
					else{
						for (int k = 0; k < tabUpdateConf[i].length; k++) {
							tabUpdateConfTMP[i][k]=tabUpdateConf[i][k];
						}
					}
				}
				setTabUpdateConf(tabUpdateConfTMP);
			}
		} catch (Exception e) {
			return false;
		}
    	return true;
    }
    
    public boolean modParticipantMicroinUpdateIHM(String dn, int newEtatMicro){
    	try {
    		if (tabUpdateConf != null){
				Object[][] tabUpdateConfTMP = new Object[tabUpdateConf.length][tabUpdateConf[0].length];
				for (int i = 0; i < tabUpdateConf.length; i++) {
					for (int k = 0; k < tabUpdateConfTMP[i].length; k++) {
						if (k==1 && tabUpdateConfTMP[i][k-1].equals(dn)){
							// change l'état du Micro avec le nouveau
							tabUpdateConfTMP[i][k]= newEtatMicro; 
						}else if (k==2 && tabUpdateConfTMP[i][k-2].equals(dn) && newEtatMicro == Constantes.MICRO_ASK){
							// Change l'état si c'est une demande de parole
							tabUpdateConfTMP[i][k]= getNumeroDemande();
							// Incr le numéro de demande
							IncrNumeroDemande();
						}else if (k==2 && tabUpdateConfTMP[i][k-2].equals(dn) && newEtatMicro == Constantes.MICRO_SPEAK){
							// Change l'état si c'est une demande de parole
							tabUpdateConfTMP[i][k]= " ";
							// Decr le numéro de demande
							DescrNumeroDemande();
						}else{
							tabUpdateConfTMP[i][k]=tabUpdateConf[i][k];
						}
					}
				}
				setTabUpdateConf(tabUpdateConfTMP);
			}
		} catch (Exception e) {
			return false;
		}
    	return true;
    }
    
    public void IncrNumeroDemande(){
    	int num = getNumeroDemande();
    	num = num++;
    		setNumeroDemande(num);
    }
    
    public void DescrNumeroDemande(){
    	int num = getNumeroDemande();
    	if (num != 1){
    		num = num--;
    		setNumeroDemande(num);
    	}	
    }

}// end of AVReceive2 
